from flask import Flask, jsonify
import pymysql

app = Flask(__name__)

# 模拟数据库连接配置
db_config = {
    'host': '192.168.81.66',
    'user': 'root',
    'passwd': '123456',
    'port': 3306,
    'db': 'HAN',
    'charset': 'utf8'
}


def connect_and_query():
    # 在函数内激活应用上下文
    with app.app_context():
        try:
            conn = pymysql.connect(**db_config)
            cursor = conn.cursor()
            sql = "SELECT * FROM dish"

            try:
                cursor.execute(sql)
                results = cursor.fetchall()
                data = [dict(zip(['Did', 'Dname', 'Dprice', 'Dsale', 'Dinv'], row)) for row in results]
                print(data)
                print(data[0])
                print(data[1])
            except Exception as e:
                conn.rollback()
                print(f"执行 SQL 查询时出错: {e}")
            finally:
                cursor.close()
                conn.close()

        except Exception as e:
            print(f"连接数据库时出错: {e}")


if __name__ == '__main__':
    connect_and_query()
